<?php declare(strict_types=1);

namespace App\Bac\Middleware;

use App\Bac\Handler\RBAC\PermissionHandler;
use App\Bac\Model\RBAC\Admin;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Helper\RespHelper;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Exception\HttpException;
use Hyperf\HttpServer\Request;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class PermissionMiddleware implements MiddlewareInterface
{

    #[Inject]
    protected Request $request;

    /**
     * @var PermissionHandler
     */
    protected PermissionHandler $permission;

    public function __construct(PermissionHandler $permission)
    {
        $this->permission = $permission;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $authAdmin = Admin::getCurAdmin();
        if ($authAdmin->username != env('SUPER_ADMIN')) {
            $permissionList = $this->permission->getUserPermissions($authAdmin->id, 1);
            $method = strtoupper($this->request->getMethod());
            $uri = str_replace(URL_PREFIX_CONTROL, '', $this->request->getRequestUri());
            $uriArr = array_filter(explode('/', $uri));
            if (count($uriArr) >= 2 && is_numeric(end($uriArr))) {
                // url 中带数字参数的清除参数
                array_pop($uriArr);
            }
            $uri = '/' . ltrim($uri, '/') . $method;
            $uri_path = "/" . implode('/', $uriArr) . "/" . $method;
            if (!in_array($uri, $permissionList) && !in_array($uri_path, $permissionList)) {
                throw new BusinessException(ErrorCode::ERR_FORBIDDEN);
            }
        }
        return $handler->handle($request);
    }
}
